package com.comac.print.component.app.command.cmdExe;

import cn.hutool.core.lang.UUID;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.comac.print.component.app.cmd.MasterPlateCmd;
import com.comac.print.component.app.common.MaterPlateCommon;
import com.comac.print.component.app.domain.gateway.print.MasterPlateGateway;
import com.comac.print.component.app.domain.gateway.printE.MasterPlateE;
import com.comac.print.component.app.dto.MasterPlateDTO;
import com.comac.print.component.app.gatewayimpl.database.dataobject.MasterPlateDO;
import com.comac.print.component.app.gatewayimpl.database.mapper.MasterPlateMapper;
import com.comac.print.component.app.utils.FileOperateUtil;
import com.comac.print.component.app.utils.NumUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class MasterPlateUploadOssCmdExe {

    @Autowired
    private FileOperateUtil fleOperateUtil;

    @Autowired
    private MasterPlateGateway masterPlateGateway;

    @Autowired
    private MasterPlateMapper masterPlateMapper;


    public SingleResponse<String> execute(MultipartFile file) {
        if (null == file) {
            return SingleResponse.buildFailure("-1", "文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return SingleResponse.buildFailure("-1", "文件不能为空");
        }
        if (!originalFilename.contains(".")) {
            return SingleResponse.buildFailure("-1", "请检查文件是否有.后缀名");
        }
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        Pattern p = Pattern.compile("^[A-Za-z]+$");
        Matcher m = p.matcher(fileType);
        if (!m.matches()) {
            return SingleResponse.buildFailure("-1", "请检查文件后缀名是否正确");
        }
        //通过UUID生成文件名
        String fileName = UUID.randomUUID().toString().toUpperCase().replace("-", "") + "." + fileType;
        String ossUrl = null;
        try {
            ossUrl = fleOperateUtil.uploadFoFile(fileName, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null == ossUrl) {
            return SingleResponse.buildFailure("-1", "上传oss失败");
        }
        return SingleResponse.of(ossUrl);
    }


    public SingleResponse<String> newExecute(MaterPlateCommon materPlateCommon) {
        MultipartFile file = materPlateCommon.getFile();
        if (null == file) {
            return SingleResponse.buildFailure("-1", "文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)) {
            return SingleResponse.buildFailure("-1", "文件不能为空");
        }
        if (!originalFilename.contains(".")) {
            return SingleResponse.buildFailure("-1", "请检查文件是否有.后缀名");
        }
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        Pattern p = Pattern.compile("^[A-Za-z]+$");
        Matcher m = p.matcher(fileType);
        if (!m.matches()) {
            return SingleResponse.buildFailure("-1", "请检查文件后缀名是否正确");
        }
        //通过UUID生成文件名
        String fileName = UUID.randomUUID().toString().toUpperCase().replace("-", "") + "." + fileType;
        String ossUrl = null;
        QueryWrapper<MasterPlateDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("system_id",materPlateCommon.getSystemId());
        queryWrapper.eq("bussiness_id",materPlateCommon.getBussinessId());
        queryWrapper.eq("version",materPlateCommon.getVersion());
        MasterPlateDO masterPlateDO = masterPlateMapper.selectOne(queryWrapper);
        // 当传入的version为空时需要校验版本时间是不是重复
        if (StringUtils.isEmpty(materPlateCommon.getVersion()) || masterPlateDO == null){
            List<MasterPlateDTO> masterPlateDOList = masterPlateMapper.qryMasterPlateByDate(materPlateCommon);
            if (!CollectionUtils.isEmpty(masterPlateDOList)){
                return SingleResponse.buildFailure("-1","升版时间重复，请检查");
            }
        }
        //先把version拿出来
        String version = materPlateCommon.getVersion();
        QueryWrapper<MasterPlateDO> queryWrappers = new QueryWrapper<>();
        queryWrappers.eq("system_id",materPlateCommon.getSystemId());
        queryWrappers.eq("bussiness_id",materPlateCommon.getBussinessId());
        queryWrappers.orderByDesc("version");
        List<MasterPlateDO> list = masterPlateMapper.selectList(queryWrappers);
        // 每次新增一定要取最大的version并且加一
        if (!CollectionUtils.isEmpty(list)){
            version = NumUtil.addNum(list.get(0).getVersion());
        }
        MasterPlateDO newMasterPlateDO = new MasterPlateDO();
        //根据传入的文件生成oss
        try {
            ossUrl = fleOperateUtil.uploadFoFile(fileName, new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null == ossUrl) {
            return SingleResponse.buildFailure("-1", "上传oss失败");
        }
        //看看传进来的版本号是否存在，如果存在就需要delete,且升版的话时启始时间不能改
        if (masterPlateDO!=null){
            masterPlateMapper.deleteById(masterPlateDO.getId());
            newMasterPlateDO.setFromVersion(masterPlateDO.getVersion());
            newMasterPlateDO.setValidEnd(masterPlateDO.getValidEnd());
            newMasterPlateDO.setValidStart(masterPlateDO.getValidStart());
        }else{
            newMasterPlateDO.setValidEnd(materPlateCommon.getValidEnd());
            newMasterPlateDO.setValidStart(materPlateCommon.getValidStart());
        }
        newMasterPlateDO.setBussinessId(materPlateCommon.getBussinessId());
        newMasterPlateDO.setOperator(materPlateCommon.getOperator());
        newMasterPlateDO.setSystemId(materPlateCommon.getSystemId());
        newMasterPlateDO.setVersion(version);
        newMasterPlateDO.setMpUrl(ossUrl);
        newMasterPlateDO.setOperatorTime(new Date());
        masterPlateMapper.insert(newMasterPlateDO);
        MaterPlateCommon plateCommon = new MaterPlateCommon();
        BeanUtils.copyProperties(materPlateCommon,plateCommon);
        plateCommon.setPlateUrl(ossUrl);
        plateCommon.setVersion(version);
        plateCommon.setFile(null);
        log.info("PrintServiceImpl uploadFile result:{}",(JSON.toJSONString(plateCommon)));
        return SingleResponse.of(JSON.toJSONString(plateCommon));
    }


    public Response saveMasterPlate(MasterPlateCmd masterPlateCmd) {
//        String currentUserCode = userInfo.getCurrentUserCode();
//        if (null == currentUserCode) {
//            return SingleResponse.buildFailure("-1", "获取当前用户信息失败");
//        }
//        String operatorName = userInfo.getUserNameByCode(attachmentUploadCmd.getOperator());
//        if (null == operatorName) {
//            return SingleResponse.buildFailure("-1", "获取操作人用户信息失败");
//        }
            MasterPlateE masterPlate = new MasterPlateE();
            BeanUtils.copyProperties(masterPlateCmd,masterPlate);
            masterPlateGateway.create(masterPlate);
        return SingleResponse.buildSuccess();
    }

    public Response masterPlateDelete(MasterPlateCmd masterPlateCmd) {
        if (masterPlateCmd.getMpId() == null) {
            return SingleResponse.buildFailure("-1", "模板的id不能为空!");
        }
        masterPlateMapper.deleteById(masterPlateCmd.getMpId());
        return SingleResponse.buildSuccess();
    }
}
